import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, UpdateResult } from 'typeorm';
import { User } from './user.entity';
import { UserLoginDto, UserUpdateDto, UserUpdatePwdDto } from './dto/user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
  ) {}
  findAll(): Promise<User[]> {
    return this.userRepository.find();
  }

  async findOneBy(data: any): Promise<User | null> {
    return await this.userRepository.findOneBy({
      ...data,
    });
  }

  async createUser(userData: UserLoginDto) {
    return this.userRepository.save(userData);
  }

  async updateUser(userData: UserUpdateDto) {
    const user = await this.userRepository.findOneBy({
      id: userData.id,
    });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }
    try {
      const result: UpdateResult = await this.userRepository.update(
        userData.id,
        userData,
      );
      if (result?.affected && result?.affected > 0) {
        return { message: '更新成功' };
      } else {
        throw new BadRequestException('更新失败');
      }
    } catch {
      throw new BadRequestException('更新失败');
    }
  }

  updateAvater(id: number, avaterUrl: string) {
    console.log('updateAvater service ', avaterUrl);

    return this.updateUser({ id, user_pic: avaterUrl });
  }

  updatePwd(body: UserUpdatePwdDto) {
    return this.updateUser({ id: body.id!, password: body.new_pwd });
  }
}
